﻿Imports System.Runtime.InteropServices
Imports Microsoft.Feeds.Interop

Public Class UpdateRSSForm
    Dim SafeSetProgress As _SetProgress
    Dim SafeShowError As _ShowError
    Dim CloseMe As _SafeClose

    Private Sub UpdateRSSForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If DwmIsCompositionEnabled() Then
            On Error Resume Next
            BackColor = Color.Black
            For Each Control As Control In Controls
                Control.BackColor = Color.Black
            Next
            VistaControls.DWM.DWMManager.EnableGlassSheet(Me)
        End If
        SafeSetProgress = New _SetProgress(AddressOf SetProgress)
        SafeShowError = New _ShowError(AddressOf ShowError)
        CloseMe = New _SafeClose(AddressOf SafeClose)
        Dim UpdateThread As New Threading.Thread(AddressOf UpdateRSSFeeds)
        UpdateThread.Start()
    End Sub

    Private Sub UpdateRSSForm_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        If DwmIsCompositionEnabled() Then
            e.Graphics.Clear(Color.Black)
        End If
    End Sub

    Sub UpdateRSSFeeds()
        Try
            Dim Feeds As List(Of IFeed) = GetFeeds(FeedsManager.RootFolder)
            For Each Feed As IFeed In Feeds
                Feed.Download()
                Invoke(SafeSetProgress, ((Feeds.IndexOf(Feed) + 1) / Feeds.Count) * 100)
            Next
            GetUnreadRSSFeeds()
        Catch ex As Exception
            Invoke(SafeShowError)
            MsgBox(ex.Message)
        End Try
        Invoke(CloseMe)
    End Sub

    Delegate Sub _SetProgress(ByVal Progress As Double)
    Sub SetProgress(ByVal Progress As Double)
        ProgressBar.Value = Progress
    End Sub

    Delegate Sub _SafeClose()
    Sub SafeClose()
        Invoke(SafeSetProgress, 0)
        Me.Close()
    End Sub

    Delegate Sub _ShowError()
    Sub ShowError()
        If DwmIsCompositionEnabled() = True Then
            ProgressBar.Value = 100
            ProgressBar.ProgressState = VistaControls.ProgressBar.States.Error
        End If
    End Sub
End Class